<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper" v-if="hasPerm('task:page')">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="工单">
                <a-select
                  :showSearch="true"
                  :filter-option="(input, option) =>{
                    return option.componentOptions.children[0].elm.data.indexOf(input) >= 0
                  }"
                  :allowClear="true"
                  style="width: 100%"
                  v-model="queryParam.workOrderId"
                  placeholder="请选择工单"
                  allow-clear >
                  <a-select-option v-for="(item,index) in list.workOrderList" :key="index" :value="item.id">{{ item.workOrderNo }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="工序名称">
                <a-select
                  :showSearch="true"
                  :filter-option="(input, option) =>{
                    return option.componentOptions.children[0].elm.data.indexOf(input) >= 0
                  }"
                  :allowClear="true"
                  style="width: 100%"
                  v-model="queryParam.workStepId"
                  placeholder="请选择工序名称"
                  allow-clear >
                  <a-select-option v-for="(item,index) in list.workStepList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="任务编码">
                  <a-input v-model.trim="queryParam.code" allow-clear placeholder="请输入任务编码" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="计划时间">
                  <a-range-picker
                    v-model="queryParam.startEndTime"
                    :show-time="{ format: 'HH:mm' }"
                    format="YYYY-MM-DD "
                    :placeholder="['开始时间', '结束时间']"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>

              <a-col :md="8" :sm="24">
                <a-form-item label="实际时间">
                  <a-range-picker
                    v-model="queryParam.factTime"
                    :show-time="{ format: 'HH:mm' }"
                    format="YYYY-MM-DD "
                    :placeholder="['开始时间', '结束时间']"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>

              <a-col :md="8" :sm="24">
                <a-form-item label="产品名称">
                  <a-select
                    :showSearch="true"
                    :filter-option="(input, option) =>{
                      return option.componentOptions.children[0].elm.data.indexOf(input) >= 0
                    }"
                    :allowClear="true"
                    style="width: 100%"
                    v-model="queryParam.proId"
                    allow-clear
                    placeholder="请选择产品名称">
                    <a-select-option v-for="(item,index) in list.proList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <a-select
                    :showSearch="true"
                    :filter-option="(input, option) =>{
                      return option.componentOptions.children[0].elm.data.indexOf(input) >= 0
                    }"
                    :allowClear="true"
                    style="width: 100%"
                    v-model="queryParam.status"
                    allow-clear
                    placeholder="请选择状态">
                    <a-select-option v-for="(item,index) in list.statusList" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="8" :sm="24" >
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" >查询</a-button>
                <a-button style="margin-left: 8px" @click="Reset">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :alert="options.alert"
        :components="this.comp"
        bordered
        :rowKey="(record) => record.id"
        :rowSelection="options.rowSelection"
        :scroll="{ x: 1500 }"
      >
        <span slot="statusScopedSlot" slot-scope="text">
          <a-tag v-if="text === 0" color="green">执行中</a-tag>
          <a-tag v-if="text === 1" color="red">已结束</a-tag>
          <a-tag v-if="text === -1" color="orange">未开始</a-tag>
        </span>

        <template class="table-operator" slot="operator" v-if="hasPerm('task:add')" >
          <!--          <a-button type="primary" v-if="hasPerm('task:add')" icon="plus" @click="$refs.addForm.add()">新增任务</a-button>-->
          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('task:delete')" @click="batchDelete"><a-icon type="delete"/>批量删除</a-button>
          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('task:start')" @click="batchStart"><a-icon type="start"/>批量开始</a-button>
          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('task:end')" @click="batchEnd"><a-icon type="end"/>批量结束</a-button>
          <x-down
            v-if="hasPerm('task:export')"
            ref="batchExport"
            @batchExport="batchExport"
          />
        </template>
        <span slot="proModelIdScopedSlots" slot-scope="text">
          {{ '${column.dictTypeCode}' | dictType(text) }}
        </span>
        <span slot="workOrderIdScopedSlots" slot-scope="text,record">
          <a-row :gutter="24">
            <a-col :md="12" :sm="24">
              {{ text }}
            </a-col>
            <a-col :md="12" :sm="24">
              <a-tag v-if="record.workOrderStatus === -1">未开始</a-tag>
              <a-tag v-if="record.workOrderStatus === 0" color="green">执行中</a-tag>
              <a-tag v-if="record.workOrderStatus === 1" color="orange">已结束</a-tag>
              <a-tag v-if="record.workOrderStatus === -2" color="purple">已取消</a-tag>
            </a-col>
          </a-row>
        </span>
        <span slot="workStepIdScopedSlots" slot-scope="text">
          {{ '${column.dictTypeCode}' | dictType(text) }}
        </span>
        <span slot="action" slot-scope="text, record">
          <a v-if="hasPerm('task:start') && record.workOrderStatus === 0" @click="() => singleStart(record)">开始</a>
          <a-divider type="vertical" v-if="hasPerm('task:start') & hasPerm('task:end') && record.workOrderStatus === 0"/>
          <a v-if="hasPerm('task:end') && record.workOrderStatus === 0" @click="() => singleEnd(record)">结束</a>
          <a-divider type="vertical" v-if="hasPerm('task:end') & hasPerm('task:detail') && record.workOrderStatus === 0"/>
          <a v-if="hasPerm('task:detail')" @click="$refs.detail.detail(record)">查看</a>
          <a-divider type="vertical" v-if="hasPerm('task:detail') & hasPerm('task:edit')"/>
          <a v-if="hasPerm('task:edit')" @click="$refs.editForm.edit(record)">编辑</a>
          <a-divider type="vertical" v-if="hasPerm('task:edit') & hasPerm('task:delete')"/>
          <a-popconfirm v-if="hasPerm('task:delete')" placement="topRight" title="确认删除？" @confirm="() => singleDelete(record)">
            <a>删除</a>
          </a-popconfirm></span>
      </s-table>
      <!--      <add-form ref="addForm" @ok="handleOk" />-->
      <edit-form ref="editForm" @ok="handleOk" />
      <detail ref="detail" @ok="handleOk" />
    </a-card>
  </div>
</template>
<script>
  import { STable, XDown } from '@/components'
  import moment from 'moment'
  import { taskPage, taskDelete, taskExport, taskStart, taskEnd } from '@/api/modular/main/task/taskManage'
  // import addForm from './addForm.vue'
  import editForm from './editForm.vue'
  import detail from './detail.vue'
  import { workOrderList } from '@/api/modular/main/workorder/workOrderManage'
  import { workStepList } from '@/api/modular/main/workstep/workStepManage'

  import { proList } from '@/api/modular/main/pro/proManage'
  import dragMixin from '@/mixins/drag/index'
  import '@/mixins/drag/drag.css'
  export default {
    components: {
      STable,
      // addForm,
      editForm,
      detail,
      XDown
    },
    mixins: [ dragMixin ],
    data () {
      return {
        list: {
          /* 状态 */
          statusList: [
            { 'name': '未开始', code: '-1' },
            { 'name': '执行中', code: '0' },
            { 'name': '已结束', code: '1' }
          ],
          workOrderList: [],
          workStepList: [],
          MoIdList: [],
          proList: []
        },
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        // 表头
        columns: [
          {
          title: '工单编号',
          ellipsis: true,
          align: 'center',
          width: 300,
          dataIndex: 'workOrderNo',
          scopedSlots: { customRender: 'workOrderIdScopedSlots' }

        },
          {
            title: '任务编码',
            align: 'center',
            dataIndex: 'code',
            width: 80,
            ellipsis: true
          },
          {
            title: '工序名称',
            ellipsis: true,
            align: 'center',
            width: 80,
            dataIndex: 'workStepName'
            //  scopedSlots: { customRender: 'workStepIdScopedSlots' }
          },
          {
            title: '报工权限',
            ellipsis: true,
            align: 'center',
            width: 80,
            dataIndex: 'sysUserName'
            // scopedSlots: { customRender: 'reportRightScopedSlots' }
          },
          {
            title: '产品名称',
            align: 'center',
            dataIndex: 'proName',
            ellipsis: true,
            width: 100,
            scopedSlots: { customRender: 'proIdScopedSlots' }
          },
          {
            title: '产品类型',
            ellipsis: true,
            align: 'center',
            width: 110,
            dataIndex: 'proTypeName',
            scopedSlots: { customRender: 'proTypeIdScopedSlots' }
          },
          {
            title: '计划开始',
            ellipsis: true,
            align: 'center',
            width: 80,
            dataIndex: 'plaStartTime'
          },
          {
            title: '计划结束',
            ellipsis: true,
            align: 'center',
            width: 80,
            dataIndex: 'plaEndTime'
          },
          {
            title: '实际开始',
            ellipsis: true,
            align: 'center',
            width: 80,
            dataIndex: 'factStaTime'
          },
          {
            title: '实际结束',
            ellipsis: true,
            align: 'center',
            width: 80,
            dataIndex: 'factEndTime'
          },
          {
            title: '良品数',
            ellipsis: true,
            align: 'center',
            width: 70,
            dataIndex: 'goodNum'
          },
          {
            title: '不良品数',
            ellipsis: true,
            align: 'center',
            width: 70,
            dataIndex: 'badNum'
          },
          {
            title: '计划数',
            ellipsis: true,
            align: 'center',
            width: 70,
            dataIndex: 'plaNum'
          },
          {
            title: '状态',
            ellipsis: true,
            align: 'center',
            width: 70,
            dataIndex: 'status',
            scopedSlots: { customRender: 'statusScopedSlot' }
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        loadData: parameter => {
          Object.assign(parameter, this.queryParam)
          if (this.queryParam.startEndTime && this.queryParam.startEndTime.length > 0) {
            const temp = []
            this.queryParam.startEndTime.forEach(item => {
              temp.push(moment(item).format('YYYY-MM-DD HH:mm'))
            })
            parameter.startEndTime = temp.join(';')
          }
          if (this.queryParam.factTime && this.queryParam.factTime.length > 0) {
            const temp = []
            this.queryParam.factTime.forEach(item => {
              temp.push(moment(item).format('YYYY-MM-DD HH:mm'))
            })
            parameter.factTime = temp.join(';')
          }

          return taskPage(parameter).then((res) => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        options: {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        }
      }
    },
    created () {
      this.visible = true
      workOrderList().then(res => {
        this.list.workOrderList = res.data
      })
      workStepList().then(res => {
        this.list.workStepList = res.data
      })

      proList().then(res => {
        this.list.proList = res.data
      })
      if (this.hasPerm('task:edit') || this.hasPerm('task:delete')) {
        this.columns.push({
          width: 230,
          title: '操作',
          align: 'center',
          fixed: 'right',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
      }
    },
    methods: {
      moment,
      /**
       * 查询参数组装
      //  */
      // switchingDate () {
      //   const queryParamfactEndTime = this.queryParam.factEndTimeDate
      //   if (queryParamfactEndTime != null) {
      //       this.queryParam.factEndTime = moment(queryParamfactEndTime).format('YYYY-MM-DD')
      //       if (queryParamfactEndTime.length < 1) {
      //           delete this.queryParam.factEndTime
      //       }
      //   }
      //   const queryParamfactStaTime = this.queryParam.factStaTimeDate
      //   if (queryParamfactStaTime != null) {
      //       this.queryParam.factStaTime = moment(queryParamfactStaTime).format('YYYY-MM-DD ')
      //       if (queryParamfactStaTime.length < 1) {
      //           delete this.queryParam.factStaTime
      //       }
      //   }
        // const queryParamplaEndTime = this.queryParam.plaEndTimeDate
        // if (queryParamplaEndTime != null) {
        //     this.queryParam.plaEndTime = moment(queryParamplaEndTime).format('YYYY-MM-DD')
        //     if (queryParamplaEndTime.length < 1) {
        //         delete this.queryParam.plaEndTime
        //     }
        // }
        // const queryParamplaStartTime = this.queryParam.plaStartTimeDate
        // if (queryParamplaStartTime != null) {
        //     this.queryParam.plaStartTime = moment(queryParamplaStartTime).format('YYYY-MM-DD')
        //     if (queryParamplaStartTime.length < 1) {
        //         delete this.queryParam.plaStartTime
        //     }
        // }
      //   const obj = JSON.parse(JSON.stringify(this.queryParam))
      //   return obj
      // },
      /**
       * 单个开始
       */
      singleStart (record) {
        const param = [{ 'id': record.id }]
        this.taskStart(param)
      },
      /**
       * 单个结束
       */
      singleEnd (record) {
        const param = [{ 'id': record.id }]
        this.taskEnd(param)
      },
      /**
       * 单个删除
       */
      singleDelete (record) {
        const param = [{ 'id': record.id }]
        this.taskDelete(param)
      },
      /**
       * 重置
       */
      Reset() {
        this.queryParam = {}
        this.$refs.table.refresh(true)
      },
      /**
       * 批量删除
       */
      batchDelete () {
        const paramIds = this.selectedRowKeys.map((d) => {
            return { 'id': d }
        })
        this.taskDelete(paramIds)
      },
      taskDelete (record) {
        taskDelete(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('删除失败') // + res.message
          }
        })
      },
      /**
       * 批量开始
       */
      batchStart () {
        const paramIds = this.selectedRowKeys.map((d) => {
          return { 'id': d }
        })
        this.taskStart(paramIds)
      },
      taskStart (record) {
        taskStart(record).then((res) => {
          if (res.success) {
            this.$message.success('开启任务成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error(res.message) // + res.message
          }
        })
      },
      /**
       * 批量结束
       */
      batchEnd () {
        const paramIds = this.selectedRowKeys.map((d) => {
          return { 'id': d }
        })
        this.taskEnd(paramIds)
      },
      taskEnd (record) {
        taskEnd(record).then((res) => {
          if (res.success) {
            this.$message.success('结束任务成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error(res.message) // + res.message
          }
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      onChangefactEndTime(date, dateString) {
        this.factEndTimeDateString = dateString
      },
      onChangefactStaTime(date, dateString) {
        this.factStaTimeDateString = dateString
      },
      onChangeplaEndTime(date, dateString) {
        this.plaEndTimeDateString = dateString
      },
      onChangeplaStartTime(date, dateString) {
        this.plaStartTimeDateString = dateString
      },
      /**
       * 批量导出
       */
      batchExport () {
        const paramIds = this.selectedRowKeys.map((d) => {
            return { 'id': d }
        })
        taskExport(paramIds).then((res) => {
            this.$refs.batchExport.downloadfile(res)
        })
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
</style>
